package com.zzzzzz.sys.role.menu;

import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.sys.menu.ZTree;

@Service
public class RoleMenuService {
	@Resource
	public RoleMenuDao roleMenuDao;
	
	@Transactional
	public int save(Long roleId, List<Long> menuIds){
		roleMenuDao.delByRoleId(roleId);
		if(menuIds != null){
			for(Long menuId : menuIds){
				roleMenuDao.add(new RoleMenu(roleId, menuId));
			}	
		}
		return 1;
	}
	
	public List<ZTree> findListByIdForEdit(Long roleId, Long id) {
		List<ZTree> zTreeList=new LinkedList<ZTree>();
		List<ZTree> list;
		if(id == null){
			list = roleMenuDao.findListByNullPidForEdit(roleId);
		}else{
			list = roleMenuDao.findListByPidForEdit(roleId, id);
		}
		
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		for(ZTree zTree:list){
			zTreeList.add(addLeafMenuForEdit(roleId, zTree));
		}
		return zTreeList;
	}
	
	private ZTree addLeafMenuForEdit(Long roleId, ZTree zTree){
		if(zTree==null){
			return null;
		}
		Long id=zTree.getId();
		if(id == null){
			return null;
		}
		
		List<ZTree> list = findListByIdForEdit(roleId, id);
		if(CollectionUtils.isEmpty(list)){
			zTree.setParent(true);
			return zTree;
		}
		zTree.setChildren(list);
		return zTree;
	}
	
	public List<ZTree> findListForSidebar(Long userId, Long platformId, Long id) {
		List<ZTree> zTreeList=new LinkedList<ZTree>();
		List<ZTree> list;
		if(id == null){
			list = roleMenuDao.findListForSidebar(userId, platformId);
		}else{
			list = roleMenuDao.findListForChildSidebar(userId, platformId, id);
		}
		
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		for(ZTree zTree:list){
			if(StringUtils.isBlank(zTree.getUrl())){
				zTree.setUrl("javascript:void(0);");
			}
			zTreeList.add(addLeafMenuForSidebar(userId, platformId, zTree));
		}
		return zTreeList;
	}
	
	private ZTree addLeafMenuForSidebar(Long userId, Long platformId, ZTree zTree){
		if(zTree==null){
			return null;
		}
		Long id=zTree.getId();
		if(id == null){
			return null;
		}
		
		List<ZTree> list = findListForSidebar(userId, platformId, id);
		if(CollectionUtils.isEmpty(list)){
			zTree.setParent(true);
			return zTree;
		}
		for(ZTree zTreeTmp : list){
			if(StringUtils.isBlank(zTreeTmp.getUrl())){
				zTreeTmp.setUrl("javascript:void(0);");
			}
		}
		
		zTree.setChildren(list);
		return zTree;
	}
}
